package com.medical.sys.service.impl;

import com.medical.common.TreeNode;
import com.medical.common.paginator.domain.PageBounds;
import com.medical.sys.mapper.OrganizationMapper;
import com.medical.sys.mapper.UserMapper;
import com.medical.sys.model.Organization;
import com.medical.sys.model.User;
import com.medical.sys.service.OrganizationService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * Created by Administrator on 2016/10/16.
 */
@SuppressWarnings("SpringJavaAutowiringInspection")
@Service("organizationService")
public class OrganizationServiceImpl implements OrganizationService {
    @Autowired
    private OrganizationMapper organizationMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public List<TreeNode> getList() {
        List<TreeNode> list = new ArrayList<TreeNode>();
        List<Organization> root = getOrganizations();
        for (Organization r : root) {
            list.add(toTreeNode(r));
        }
        return list;
    }

    public List<Organization> getOrganizations() {
        return getOrganizations(false);
    }

    public List<Organization> getOrganizations(Boolean administrator) {
        return organizationMapper.selectAll(administrator);
    }

    private TreeNode toTreeNode(Organization organization) {
        TreeNode node = new TreeNode();
        node.setId(String.valueOf(organization.getId()));
        node.setName(organization.getName());
        node.setParentId(organization.getParentId());
        return node;
    }

    public Organization getOrganization(String organizationId) {
        Organization organization = organizationMapper.selectByPrimaryKey(organizationId);
        List<User> users = userMapper.selectByOrgId(organizationId);
        for(User user : users) {
            if(organization != null) {
                organization.getUserIds().add(user.getId());
            }
        }
        return organization;
    }
    public void saveOrganization(Organization organization) {

        if(organization != null){
            if(StringUtils.isEmpty(organization.getId())){
                organization.setId(UUID.randomUUID().toString());
            }
            if(StringUtils.isEmpty(organization.getName())){
                throw new CustomizeException("name不能为空 ");
            }
            if(StringUtils.isEmpty(organization.getParentId())){
                throw new CustomizeException("parentid不能为空");
            }
            Organization parent = getOrganization(organization.getParentId());//返回的是携带这个Organization的UserId集合的Organization对象
                                                                              //getOrganization(String organizationid)
            if(parent != null){
                organization.setParentIdsStr(parent.getSelfForParent());
            }else{
                organization.setParentIdsStr("0");
            }
            organizationMapper.insert(organization);
        }
        else {
            throw new CustomizeException("输入的门店不能为空");
        }
    }

    public void updateOrganization(Organization organization) {
        Organization parent = getOrganization(organization.getParentId());
        if(parent != null) {
            organization.setParentIdsStr(parent.getSelfForParent());
        }else{
            organization.setParentIdsStr("0");
        }
        organizationMapper.updateByPrimaryKey(organization);
    }


    public void deleteOrganization(String organizationId) {
        deleteOrganization(organizationId, false);
    }

    public void deleteOrganization(String organizationId, Boolean administrator) {
        if(administrator){
            organizationMapper.deleteByPrimaryKey(organizationId);
        }else{
            Organization organization = organizationMapper.selectByPrimaryKey(organizationId);
            if(organization != null){
                organization.setDeleted(true);
                organizationMapper.updateByPrimaryKey(organization);
            }
        }
    }

    public void moveOrganization(String id, String targetId, String moveType) {
        Organization organization = organizationMapper.selectByPrimaryKey(id);
        Organization target = organizationMapper.selectByPrimaryKey(targetId);
        String sourceParentId = organization.getParentId();
        String parentId = "0";
        switch (moveType){
            case "inner":
                parentId = targetId;
                break;
            default:
                if(target != null) {
                    parentId = target.getParentId();
                }
                break;
        }
        List<Organization> childrens = organizationMapper.selectByParentId(parentId);
        if(!parentId.equals(sourceParentId)) {
           organization.setParentId(parentId);
        }
        Integer priority = 0;
        for(Organization children : childrens){
            if(!id.equals(children.getId())) {
                if (!targetId.equals(children.getId())) {
                    children.setPriority(priority);
                    priority++;
                } else {
                    switch (moveType) {
                        case "inner":
                            organization.setPriority(childrens.size());
                            break;
                        case "prev":
                            organization.setPriority(priority);
                            children.setPriority(priority + 1);
                            priority = priority + 2;
                            break;
                        case "next":
                            children.setPriority(priority);
                            organization.setPriority(priority + 1);
                            priority = priority + 2;
                            break;
                    }
                }
            }
            updateOrganization(children);
        }
        updateOrganization(organization);
        if(!parentId.equals(sourceParentId)){//同级移动时不修改旧子集
            List<Organization> oldChildrens = organizationMapper.selectByParentId(sourceParentId);
            for(int j=0;j<oldChildrens.size();j++){
                Organization oldChildren = oldChildrens.get(j);
                oldChildren.setPriority(j);
                updateOrganization(oldChildren);
            }
        }
    }

}
